﻿using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Drawing;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SqlSugar;
using System.Xml.Linq;
using AutoUpdaterDotNET;
using DevExpress.ClipboardSource.SpreadsheetML;
using SqlSugar.Extensions;
using WinformDevelopFrame.Core.Extend;
using WinformDevelopFrame.IServices;
using WinformDevelopFrame.Services;
using WinformDevelopFrame.Common;
using WinformDevelopFrame.Entity;

namespace WinformDevelopFrame.UI
{
    public partial class FrmLogin : DevExpress.XtraEditors.XtraForm
    {
        private Point mPoint;
        private IsysuserService _sysuserService;
        private ISqlSugarClient _sqlSugarClient;
        private IsysmenuService _sysmenuService;
        public FrmLogin(IsysuserService sysuserService, ISqlSugarClient sqlSugarClient, IsysmenuService sysmenuService)
        {
            _sysuserService = sysuserService;
            _sqlSugarClient = sqlSugarClient;
            _sysmenuService = sysmenuService;
            InitializeComponent();
        }

        private void LoginForm_MouseDown(object sender, MouseEventArgs e)
        {
            mPoint = new Point(e.X, e.Y);
        }

        private void LoginForm_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                this.Location = new Point(this.Location.X + e.X - mPoint.X, this.Location.Y + e.Y - mPoint.Y);
            }
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            login();
        }

        private void login()
        {
            if (string.IsNullOrEmpty(textEdit1.Text))
            {
                XtraMessageBox.Show("请输入用户名");
                textEdit1.Focus();
                return;
            }
            if (string.IsNullOrEmpty(textEdit2.Text))
            {
                XtraMessageBox.Show("请输入密码");
                textEdit2.Focus();
                return;
            }
            var user = _sysuserService.QueryListByClause(p => p.LoginAccount.Equals(textEdit1.Text)).FirstOrDefault();
            if (user == null)
            {
                "用户不存在".ShowTips();
                return;
            }

            if (!textEdit2.Text.Equals(user.Password))
            {
                "密码错误！".ShowTips();
                return;
            }
            //修改最后登录时间
            user.LoginLastTime = DateTime.Now;
            _sysuserService.Update(user);
            AppInfo.User = user;
            //获取功能权限
            var menuIds = _sqlSugarClient.Queryable<sysrolemenu>().Where(p => p.RoleId == user.RoleId).Select(p=>p.MenuId);
            List<sysmenu> menus= _sysmenuService.QueryByIDs(menuIds.ToArray());
            AppInfo.Menus = menus;
            AppInfo.User.LoginStatus = LoginStatus.Login;
            System.Net.IPHostEntry hostIP = System.Net.Dns.GetHostEntry(Environment.MachineName);
            AppInfo.User.IP = hostIP.AddressList[0].ToString();
            _sysuserService.UpdateN(AppInfo.User);
            this.DialogResult = DialogResult.OK;
        }
        private void simpleButton2_Click(object sender, EventArgs e)
        {
            this.Close();
        }


        private void LoginForm_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                login();
            }
        }

        private void LoginForm_Load(object sender, EventArgs e)
        {
            if (ConfigurationManager.AppSettings["AtuoUpdate"].ObjToBool())
            {
                AutoUpdater.CheckForUpdateEvent += AutoUpdater_CheckForUpdateEvent;
                AutoUpdater.ApplicationExitEvent += AutoUpdater_ApplicationExitEvent;
                AutoUpdater.Start(ConfigurationManager.AppSettings["UpdateUrl"]);
            }

        }
        private void AutoUpdater_ApplicationExitEvent()
        {

        }

        private void AutoUpdater_CheckForUpdateEvent(UpdateInfoEventArgs args)
        {
            if (args != null && new Version(args.CurrentVersion).CompareTo(new Version(ConfigurationManager.AppSettings["Version"])) > 0)
            {
                FrmUpdate frm = new FrmUpdate();
                frm.url = args.ChangelogURL;
                frm.newVsersion = args.CurrentVersion;
                frm.oldVersion = ConfigurationManager.AppSettings["Version"];
                var dialogResult = frm.ShowDialog();
                if (dialogResult == DialogResult.Yes)
                {
                    if (AutoUpdater.DownloadUpdate(args))
                    {
                        Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                        configuration.AppSettings.Settings["Version"].Value = args.CurrentVersion;
                        configuration.Save(ConfigurationSaveMode.Modified);
                        Application.Exit();
                    }
                }
            }
        }
    }
}